package com.hb.trade.api.routine.controller.project.archive;

import cn.hutool.json.JSONObject;
import com.hb.core.pojo.Attachment;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.project.archive.dto.ArchiveCommonFileDTO;
import com.hb.core.pojo.project.archive.dto.ProjectArchiveFileDTO;
import com.hb.core.pojo.project.archive.entity.ProjectArchiveFile;
import com.hb.trade.client.project.ProjectArchiveFileClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.file.base.FileBaseController;
import org.fzzn.core.file.entity.HbFileInfo;
import org.fzzn.core.file.service.DownloadService;
import org.fzzn.core.file.service.PersistenceService;
import org.fzzn.core.model.constant.CommonConstant;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.service.ZipFileService;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author ：YueZheng
 * @description：TODO
 * @date ：2022/2/17 10:27 上午
 */
@Slf4j
@Version(1.0)
@Api(tags = {"归档文件"})
@RestController
@RequestMapping("/{version}")
public class ApiArchiveFileController extends FileBaseController {

    @Autowired
    private ProjectArchiveFileClient projectArchiveFileClient;

    @Autowired
    private DownloadService downloadService;
    private List<HbFileInfo> hbFileInfos;

    public ApiArchiveFileController(PersistenceService persistenceService) {
        super(persistenceService);
    }

    /**
     * 查询文件
     *
     * @param projectArchiveFileDTO
     * @return
     */
    @PostMapping("/archive/file/info")
    public ResponseDto info(@RequestBody ProjectArchiveFileDTO projectArchiveFileDTO) {
        JSONObject extInfo = ShiroUtil.getExtInfo();
        String orgName = extInfo.getStr("orgName");
        projectArchiveFileDTO.setOrgName(orgName);
        Message<Object> message = this.projectArchiveFileClient.info(projectArchiveFileDTO);
        return ResultUtil.msg(message);
    }

    /**
     * @param projectArchiveFile:
     * @Description: 添加文件类型
     * @Author: yuezheng
     * @Date:2021/12/22 16:39
     * @return: {@link Message <  Boolean > }
     **/
    @ApiOperation(value = "归档文件类型新增", notes = "归档文件类型新增", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileType", value = "文件名称", dataTypeClass = Attachments.class),
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataTypeClass = String.class),
    })
    @PostMapping("/archive/type/add")
    public ResponseDto addArchiveType(@RequestBody ProjectArchiveFile projectArchiveFile) {
        Message<Boolean> result = projectArchiveFileClient.addArchiveType(projectArchiveFile);
        return ResultUtil.success(result.getMessage());
    }

    /**
     * @param projectArchiveFile:
     * @Description: 添加文件
     * @Author: yuezheng
     * @Date:2021/12/22 16:39
     * @return: {@link Message <  Boolean > }
     **/
    @ApiOperation(value = "归档文件新增", notes = "归档文件新增", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "类型id", dataTypeClass = String.class),
            @ApiImplicitParam(name = "file_url", value = "服务器地址", dataTypeClass = String.class),
            @ApiImplicitParam(name = "file_size", value = "文件大小", dataTypeClass = String.class),
            @ApiImplicitParam(name = "file_path", value = "文件路径", dataTypeClass = String.class),
            @ApiImplicitParam(name = "rawFileAme", value = "文件名称", dataTypeClass = Attachments.class),
            @ApiImplicitParam(name = "did", value = "文件类型id", dataTypeClass = String.class),
            @ApiImplicitParam(name = "note", value = "备注", dataTypeClass = String.class),
    })
    @PostMapping("/archive/file/add")
    public ResponseDto addArchiveFile(@RequestBody ProjectArchiveFile projectArchiveFile) {
        Message<Boolean> result = projectArchiveFileClient.addArchiveFile(projectArchiveFile);
        return ResultUtil.success(result.getMessage());
    }


    /**
     * 下载指定ID的文件
     *
     * @param projectArchiveFileDTO
     * @return
     * @update 岳争
     */
    @ApiOperation(value = "下载指定文件名称的文件", notes = "下载指定文件名称的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileId", value = "文件id", dataTypeClass = String.class)
    })
    @RequestMapping("/archive/file/down")
    public void downloadFileByName(@RequestBody ProjectArchiveFileDTO projectArchiveFileDTO, HttpServletResponse response) {

        Message<Attachments> message = projectArchiveFileClient.getAttachments(projectArchiveFileDTO);

        Attachments data = message.getData();
        List<Attachment> attachmentList = data.stream().filter(item -> item.getId() != null).filter(item ->
                 item.getId().equals(Long.valueOf(projectArchiveFileDTO.getFileId()))
       ).collect(Collectors.toList());

        if (data.size() <= 0) {
            log.warn(MsgEnum.INCORRECT_PARAM.msg());
            return;
        }
        Attachment attachment = attachmentList.get(0);

        File file = attachment.getThisFile();

        downloadService.download(attachment.getRawFileName() + CommonConstant.COMMA + attachment.getExtName(),
                file, response);
    }


    /**
     * 打包下载指定归档的文件列表
     *
     * @param projectArchiveFileDTO
     * @return
     * @update 岳争
     */
    @ApiOperation(value = "打包下载指定归档的文件列表", notes = "打包下载指定归档的文件列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "归档ID", dataTypeClass = String.class)
    })
    @RequestMapping("/archive/file/section")
    public void downloadFileZipBySectionId(@RequestBody ProjectArchiveFileDTO projectArchiveFileDTO, HttpServletResponse response) {
        JSONObject extInfo = ShiroUtil.getExtInfo();
        String orgName = extInfo.getStr("orgName");
        projectArchiveFileDTO.setOrgName(orgName);
        // 获取所有要下载的文件
        Message<Attachments> message = projectArchiveFileClient.getAttachments(projectArchiveFileDTO);

        Attachments data = message.getData();

        if (data.size() <= 0) {
                log.warn(MsgEnum.INCORRECT_PARAM.msg());
                return;
        }

        // 取第一个文件名作为压缩包的名字
        String finalName = data.get(0).getFileName();

        // 构建压缩包文件, 并添加文件
        ZipFileService zipFileService = ZipFileService.getInstance();
        for (Attachment fileInfo : data) {
            File file = fileInfo.getThisFile();
            zipFileService.add(fileInfo.getRawFileName() + UUID.randomUUID().toString() + CommonConstant.COMMA + fileInfo.getExtName(), file);
        }

        // 生成下载文件
        File file = zipFileService.file(finalName + CommonConstant.COMMA + "zip");
        downloadService.download(file.getName(), file, response);
    }


    /**
     * 删除文件
     *
     * @Param: id
     * @return: ResponseDto
     * @Author: 岳争
     * @Date: 2022/2/17
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileType", value = "文件类型", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "sectionId", value = "归档id", dataTypeClass = Long.class),
    })
    @PostMapping("/archive/file/delById")
    public ResponseDto deleteArchiveFile(@RequestBody ProjectArchiveFileDTO projectArchiveFileDTO) {
        Message<Boolean> result = projectArchiveFileClient.deleteArchiveFile(projectArchiveFileDTO);
        return ResultUtil.success(result.getMessage());
    }


    /**
     * 删除单个文件
     *
     * @Param: projectArchiveDetailVo
     * @return: ResponseDto
     * @Author: 岳争
     * @Date: 2022/2/17
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文件类型ID", dataTypeClass = String.class),
            @ApiImplicitParam(name = "fileId", value = "文件ID", dataTypeClass = String.class),
    })
    @PostMapping("/archive/file/del")
    public ResponseDto deleteByFileId(@RequestBody ProjectArchiveFileDTO projectArchiveFileDTO) {
        Message<Boolean> result = projectArchiveFileClient.deleteByFileid(projectArchiveFileDTO);
        return ResultUtil.success(result.getMessage());
    }


}
